#ifndef __BLOCK_QUEUE_HPP__
#define __BLOCK_QUEUE_HPP__
#include <iostream>
#include <queue>
#include <pthread.h>
template <class T>
class BlockQueue
{
public:
    bool IsFull()
    {
        return _cap = _block_queue.size();
    }
    bool IsEmpty()
    {
        return _block_queue.empty();
    }
    BlockQueue(int cpa) : _cap(cap)
    {
        _productor_wait_num=0;
        _consumer_wait_num=0;
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_product_cond, nullptr);
        pthread_cond_init(&_consum_cond, nullptr);
    }
    void Enqueue(const T &in) // 生产者的接口
    {
        pthread_mutex_lock(&_mutex);
        while (IsFull())
        {
            _productor_wait_num++;
            pthread_cond_wait(&_product_cond, &_mutex);
            _productor_wait_num--;
        }
        // 进行生产
        //_block_queue.push(move(in));
        _block_queue.push(in);
        // 通知消费者来消费
        if(_consumer_wait_num>0)
            pthread_cond_signal(&_consum_cond);
        pthread_mutex_unlock(&_mutex);
    }
    void Pop(T *out) // 消费者的接口
    {
        pthread_mutex_lock(&_mutex);
        while (IsEmpty())
        {
            _consumer_wait_num++;
            pthread_cond_wait(&_consum_cond, &_mutex);
            _consumer_wait_num--;
        }
        // 进行消费
        *out = _block_queue.front();
        _block_queue.pop();
        // 通知生产者来生产
        if(_productor_wait_num>0)
            pthread_cond_signal(&_product_cond);
        pthread_mutex_unlock(&_mutex);
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_product_cond);
        pthread_cond_destroy(&_consum_cond);
    }

private:
    queue<T> _block_queue;        // 阻塞队列
    int _cap;                     // 总上限
    pthread_mutex_t _mutex;       // 保护 _block_queue的锁
    pthread_cond_t _product_cond; // 专门给生产者提供的条件变量
    pthread_cond_t _consum_cond;  // 专门给消费者提供的条件变量
    int _productor_wait_num;
    int _consumer_wait_num;
};
#endif